/**!
 * cnpmjs.org - dispatch.js
 *
 * Copyright(c) cnpmjs.org and other contributors.
 * MIT Licensed
 *
 * Authors:
 *  dead_horse <dead_horse@qq.com>
 *  fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
 */

'use strict';

/**
 * Module dependencies.
 */

var path = require('path');
var fs = require('fs');
var util = require('util');
var cfork = require('cfork');
var C = require('./config');
var workerPath = path.join(__dirname, 'worker.js');

// 启动字词过滤服务器
var server = require('sc-filter').createServer();

if (C.wordFilter.unix_socket) { // Unix Socket 方式
    if (fs.existsSync(C.wordFilter.unix_socket)) {
        fs.unlinkSync(C.wordFilter.unix_socket);
    }
    server.set('connectStr', C.wordFilter.unix_socket);
} else { // TCP 方式
    server.set('connectStr', C.wordFilter.port);
}

server.loadDict(function loaded() {
    server.listen(server.get('connectStr'), function () {
        console.log('Dict server is listening on ' + server.get('connectStr'));
    });
});

if (C.enableCluster) {
    forkWorker();
} else {
    require(workerPath);
}

function forkWorker() {
    cfork({
        exec: workerPath,
        count: C.numCPUs
    }).on('fork', function (worker) {
        console.log('[%s] [worker:%d] new worker start', Date(), worker.process.pid);
    }).on('disconnect', function (worker) {
        console.error('[%s] [master:%s] wroker:%s disconnect, suicide: %s, state: %s.',
            Date(), process.pid, worker.process.pid, worker.suicide, worker.state);
    }).on('exit', function (worker, code, signal) {
        var exitCode = worker.process.exitCode;
        var err = new Error(util.format('worker %s died (code: %s, signal: %s, suicide: %s, state: %s)',
            worker.process.pid, exitCode, signal, worker.suicide, worker.state));
        err.name = 'WorkerDiedError';
        console.error('[%s] [master:%s] wroker exit: %s', Date(), process.pid, err.stack);
    });
}
